package com.lc.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

import org.junit.Test;

/**
 * @author 逝兮诚
 * @date 2017年6月20日 上午11:05:06 
 * @see tcp 连接与数据传输 http请求实现
 */
public class SocketChannelTest {

	@Test
	public void testClient() throws IOException {
		SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
		socketChannel.configureBlocking(false);
		ByteBuffer bBuffer = ByteBuffer.allocate(48);
		for (int readSize = socketChannel.read(bBuffer); readSize != -1; readSize = socketChannel.read(bBuffer)) {
			if (readSize == 0)
				continue;
			bBuffer.flip();
			System.out.println(Charset.forName("UTF-8").decode(bBuffer));
			bBuffer.clear();
		}
		socketChannel.close();
	}

	@Test
	public void testServer() throws IOException {
		ServerSocketChannel server = ServerSocketChannel.open();
		server.socket().bind(new InetSocketAddress(9999));
		System.out.println("服务端启动成功");
		server.configureBlocking(false);
		while (true) {
			SocketChannel socketChannel = server.accept();
			if (socketChannel != null) {
				System.out.println(socketChannel + "连接成功");
				ByteBuffer bBuffer = ByteBuffer.wrap(("服务器" + server + "连接成功").getBytes("UTF-8"));
				bBuffer.rewind();
				while (bBuffer.hasRemaining()) {
					socketChannel.write(bBuffer);
				}
				socketChannel.close();
			}
		}
	}
}
